<template>
  <div class="home-page">
    <el-container>
      <el-header style="padding:0">
        <el-menu
          router
          :default-active="$route.path"
          :ellipsis="false"
          class="el-menu-demo"
          mode="horizontal"
        >
          <img class="logo" src="../assets/image/logo.png" style="margin-left:20px"/>
          <div class="place-holder"/>
          <el-menu-item index="/MainPage/Market">市场</el-menu-item>
          <el-sub-menu index="/MainPage/ListDeal">
            <template #title>订单</template>
            <el-menu-item index="/MainPage/ListBuy">求购单</el-menu-item>
            <el-menu-item index="/MainPage/ListSale">供应单</el-menu-item>
            <el-menu-item index="/MainPage/ListDeal">交易单</el-menu-item>
          </el-sub-menu>
          <el-menu-item disabled>社区</el-menu-item>
          <el-sub-menu index="/MainPage/UserInfo" v-if="isLogin">
            <template #title><el-avatar shape="circle" :size="30" :src="squareUrl" style="margin-right:10px"/>{{nickname}}</template>
            <el-menu-item index="/MainPage/UserInfo">个人信息</el-menu-item>
            <el-menu-item index="/MainPage/UserAccount">账户<div style="color: rgb(235, 167, 65);margin-left:10px">{{balance}}</div></el-menu-item>
            <el-menu-item @click="logout()" index="/LoginPage">退出</el-menu-item>
          </el-sub-menu>
          <el-menu-item index="/LoginPage" v-else>登录</el-menu-item>
        </el-menu>
      </el-header>
      <el-container>
        <el-main style="padding:0"><router-view/></el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import store from '@/store'
import { userInfo, userLogout } from '../http/api/user'
import { balance } from '../http/api/cash'
import { serverConfig } from "../http/config"

export default {
  data() {
    return {
      squareUrl: null,
      nickname: null,
      balance: 0,
      isLogin: false
    }
  },
  methods: {
    logout: function() {
      userLogout()
      .then((res) => {
        store.dispatch("changeLoginStatus", null)
        localStorage.clear()
      })
      this.isLogin = false
    }
  },
  created: function() {
    let claims = localStorage.getItem("claims")
    if (claims != null) {
      let info = JSON.parse(claims)
      this.isLogin = true
      this.nickname = info.nickname
      let that = this
      userInfo()
      .then((res) => {
        if (res != null) {
          that.squareUrl = serverConfig.baseURL + "/usercenter/nil/image/" +res.data.data.ProfilePhotoHash
        }
      })
      balance()
      .then((res) => {
        that.balance = res.data.data
      })
    } else {
      this.isLogin = false
    }
  },
  mounted: function() {
  }
}
</script>

<style lang="less" scoped>
  .home-page {
    min-height: 100vh;
    .logo {
      height: 60px;
      width: 60px;
    }
    .place-holder {
      flex-grow: 1;
    }
  }
</style>